# -*- coding: utf-8 -*-
from django.shortcuts import render
from datetime import datetime
from .forms import SelectTempleteForm
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.core import serializers
from django.forms.models import model_to_dict
import redis
import re
from django.views.generic import View
from yisheng.models import User_Sites, User, Contract
from company_manage.models import YsbCompanyInfo, BaiduAppCompanyInfo, ClarkiiSeoCompanyInfo, SmsCompanyInfo, \
    AllCompanyInfo
from django.http import JsonResponse, HttpResponse
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
import json
import uuid
from django.core.cache import cache
from dysms_python.demo_sms_send import send_sms
from message_backup.models import SendResult
from message_model.models import MessageTemplet
from baidu_app.models import Company_Backup
from clarkii_seo.models import SeoSysUser, SeoUserBusiness
from BeeBos import settings
import logging
def SelectMobile(request):
    # BeeBos\extra_apps\xadmin\templates\xadmin\blocks\model_list.results_bottom.actions.html
    pool = redis.ConnectionPool(host=settings.redis_host, port=6379, password='123456')
    r = redis.Redis(connection_pool=pool)
    r.delete('mobiles')

    mobileJson = request.POST.get('mobileJson')
    modelName = request.POST.get('modelName')
    if (mobileJson != None):
        mobileList = json.loads(mobileJson)
        for m in mobileList:
            r.rpush("mobiles", m)

    else:
        # 取出全部手机号
        if 'ysbcompanyinfo' in modelName:
            ysb_qs = YsbCompanyInfo.objects.exclude(mobile='')  # 过滤空号码
            for q in ysb_qs:
                r.rpush('mobiles', q.mobile.strip().replace("\n", ""))  # 将手机号先存入redis
        elif 'baiduappcompanyinfo' in modelName:
            baidu_qs = BaiduAppCompanyInfo.objects.exclude(phone_number='')
            for q in baidu_qs:
                r.rpush('mobiles', q.phone_number.strip().replace("\n", ""))
        elif 'clarkiiseocompanyinfo' in modelName:
            clarkiiseo_qs = ClarkiiSeoCompanyInfo.objects.exclude(mobile='')
            for q in clarkiiseo_qs:
                r.rpush('mobiles', q.mobile.strip().replace("\n", ""))
        elif 'smscompanyinfo' in modelName:
            sms_qs = SmsCompanyInfo.objects.exclude(phone='')
            for q in sms_qs:
                r.rpush('mobiles', q.phone.strip().replace("\n", ""))
        elif 'allcompanyinfo' in modelName:
            all_qs = AllCompanyInfo.objects.exclude(phone='')
            for q in all_qs:
                r.rpush('mobiles', q.phone.strip().replace("\n", ""))

    r.expire('mobiles', 300)  # 保存手机号时间为5分钟

    templetes = MessageTemplet.objects.filter(status=2,template_type=3)
    data = {
        'resu':"success",
        'total': len(templetes),
        'rows': [model_to_dict(item) for item in templetes]
    }
    return JsonResponse(data)


def SendTemplete(request):
    templeteCode = request.POST.get('templeteCode')
    signName = request.POST.get('signName')
    pool = redis.ConnectionPool(host=settings.redis_host, port=6379, password='123456')
    r = redis.Redis(connection_pool=pool)
    mobilelist = r.lrange('mobiles', 0, r.llen("mobiles") - 1)
    mobileset = set(mobilelist)
    mobilelist = list(mobileset)
    if (len(mobilelist) < 1):
        return JsonResponse({'resu': "您预选的手机号已过保存时间，请重新选择！"})
    sendMobile = ""

    quotient = len(mobilelist) // 1000  # 商
    remainder = len(mobilelist) % 1000  # 余数
    index = 1
    phone_pat = re.compile('^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$')
    result=""
    while index <= quotient:
        s = 1000 * (index - 1)
        for mobile in mobilelist[s:index * 1000]:
            mobileStr = str(mobile, encoding = "utf-8").strip().replace("\n", "").replace('\t','')
            res = re.search(phone_pat,mobileStr)
            if res == None:
                continue
            sendMobile = sendMobile + mobileStr + ","
        sendMobile = sendMobile[:-1]
        __business_id = uuid.uuid1()
        #resultJson = {'Message': 'OK', 'RequestId': 'EE13747F-7509-4157-939A-F82CE4DF50A3', 'BizId': '642113333708761184^0','Code': 'OK'}
        resultJson = json.loads(send_sms(__business_id, sendMobile, signName, templeteCode, None))
        logging.info('批量发送回执：', resultJson)
        result = SaveSendRecord(resultJson, request, 1000, sendMobile)
        index += 1
        sendMobile=""

    if(remainder>0):
        for m in mobilelist[quotient * 1000:len(mobilelist)]:
            mStr = str(m, encoding="utf-8").strip().replace("\n", "").replace('\t', '')
            res = re.search(phone_pat, mStr)
            if res == None:
                continue
            sendMobile = sendMobile + mStr + ","
        sendMobile = sendMobile[:-1]
        __business_id = uuid.uuid1()
        #resultJson = {'Message': 'OK', 'RequestId': 'EE13747F-7509-4157-939A-F82CE4DF50A3','BizId': '642113333708761184^0','Code': 'OK'}
        resultJson = json.loads(send_sms(__business_id, sendMobile, signName, templeteCode, None))
        logging.info('批量发送回执：', resultJson)
        result = SaveSendRecord(resultJson, request, remainder, sendMobile)
    return JsonResponse({"resu": result})


def SaveSendRecord(resultJson, request, mobilelen, mobile):
    templeteCode = request.POST.get('templeteCode')
    templeteId = request.POST.get('templeteId')
    templete = request.POST.get('templete')
    signName = request.POST.get('signName')
    companyinfo = request.POST.get('companyinfo')
    mobileLen = mobilelen
    createtime = datetime.now()
    result = ""

    sendResult = SendResult()
    sendResult.template_id = templeteId
    sendResult.template_code = templeteCode
    sendResult.sign_name = signName
    sendResult.template = templete
    if 'Message' in resultJson:
        sendResult.message = resultJson['Message']
    if 'RequestId' in resultJson:
        sendResult.request_id = resultJson['RequestId']
    if 'BizId' in resultJson:
        sendResult.biz_id = resultJson['BizId']
    if 'Code' in resultJson:
        sendResult.code = resultJson['Code']
    sendResult.create_time = createtime
    sendResult.mobile_len = mobileLen
    sendResult.companyinfo = companyinfo
    sendResult.mobile = mobile

    SendResult.save(sendResult)
    if (resultJson['Code'] == "OK"):
        result = "发送成功"
    elif (resultJson['Code'] == 'isv.SMS_TEMPLATE_ILLEGAL'):
        result = "模板不存在或被拉黑"
    elif (resultJson['Code'] == 'isv.SMS_SIGNATURE_ILLEGAL'):
        result = "短信签名不存在或不合法"
    elif (resultJson['Code'] == 'isv.OUT_OF_SERVICE'):
        result = "业务停机"
    elif (resultJson['Code'] == 'isp.RAM_PERMISSION_DENY'):
        result = "RAM权限DENY"
    else:
        result = "发送短信失败，请联系开发人员！"
    return result
